<template>
	<div class="order-tracking-container">
		<header ref="box1" class="" style="">
			<el-row class="flex-start-center" style="align-items: flex-end;">
				<el-col :span="6">
					<workshop-search
						:search-params="searchParams"
						:workshop-list="workshopList"
						@on-change="onSelectDropdown"
					></workshop-search>
					<el-button size="mini" type="primary">订单: {{ orderOption ? orderOption.length : 0 }}, 在产: {{ orderOption ? orderOption.filter(x => x.ifOpen).length : 0 }}</el-button>
				</el-col>
				<el-col :span="12" class="flex-start-center">
					<el-autocomplete
						v-model="searchParams.customerName"
						:fetch-suggestions="querySearchAsync"
						placeholder="客户名称"
						size="large"
						:popper-append-to-body="false"
						style="width: 100%;"
						class="item-gap"
						clearable
						@select="onSelectCutomerChange"
					></el-autocomplete>
					<el-button :loading="searchBtnLoading" icon="el-icon-search" type="primary" size="large" @click="onSearchBtn"></el-button>
				</el-col>
				<el-col :span="6" class="flex-end-center">
					<el-button size="mini" class="item-gap" type="primary" @click="onJumpBtn">二维表</el-button>
					<jk-full-screen-button class-name="order-tracking-container" @status="(e) => isFullScreen = e"></jk-full-screen-button>
				</el-col>
			</el-row>
		</header>
		<!--图例-->
		<order-list
			:select-order-item="selectOrderItem"
			:order-option="orderOption"
			@on-item="onOrderItem"
		></order-list>
		<!--区域布局-->
		<div style="width: 100%;height: calc(100% - 198px);">
			<workshop-layout
				:is-full-screen="isFullScreen"
				:layout-data="allWorkshopLayoutList"
				@on-status="onSelectMachineItem"
			></workshop-layout>
		</div>
		<!--机台运转详情-->
		<machine-run-params-detail-dialog
			ref="machineParamsDialog"
			:machine-data="selectMachineData"
			:dialog-state="machineRunParamsDetailDialogState"
			@on-visible-change="onVisibleChangeOfMachineRunParamsDetailDialog"
		></machine-run-params-detail-dialog>
	</div>
</template>
<script>
    import {
        intelligenceReportWorkshopLayoutGetByWorkshopIds
    } from '../../../api/intelligence';
    import VueGridLayout from 'vue-grid-layout';
    import { reportProductionOrderTracking } from '../../../api/production/productionMonitor';
    import colorMixin from './colors-mixin';
    import { spinCustomerPage } from '../../../api/personnel/customer';
    import machineRunParamsDetailDialog from '../machineStateMonitor/detail-dialog';
    import workshopSearch from './components/workshop-search';
    import workshopLayout from './components/workshop-layout';
    import orderList from './components/order-list';

    export default {
        mixins: [colorMixin],
        components: {
            orderList,
            workshopLayout,
            workshopSearch,
            machineRunParamsDetailDialog,
            GridLayout: VueGridLayout.GridLayout,
            GridItem: VueGridLayout.GridItem
        },
        data() {
            return {
                machineRunParamsDetailDialogState: false,
                selectMachineData: {},
                isFullScreen: true,
                searchBtnLoading: false,
                allWorkshopLayoutList: [],
                workshopList: [],
                selectOrderItem: {},
                searchParams: {
                    workshopIds: [],
                    customerName: '',
                    ifTest: false,
                    serviceStates: [0, 1, 2, 3]
                },
                orderOption: [],
                ruleForm: {
                    colNum: 48,
                    rowHeight: 4,
                    workshopId: null,
                    workshopCode: '',
                    workshopName: ''
                }
            };
        },
        methods: {
            onSelectMachineItem(item) {
                this.selectMachineData = item;
                this.machineRunParamsDetailDialogState = true;
            },
            onVisibleChangeOfMachineRunParamsDetailDialog(e) {
                this.machineRunParamsDetailDialogState = e;
            },
            onJumpBtn() {
                this.$toMainRouter({
                    name: 'OrderOpenDetail'
                });
            },
            onSelectDropdown(e) {
                const checked = this.searchParams.workshopIds.includes(e);
                if (checked) {
                    this.searchParams.workshopIds.forEach((item, index) => {
                        if (item === e) {
                            this.searchParams.workshopIds.splice(index, 1);
                        }
                    });
                } else {
                    this.searchParams.workshopIds.push(e);
                }
                this.getAllWorkshopLayoutList();
            },
            onSelectCutomerChange(e) {
                if (e) {
                    this.$set(this.searchParams, 'customerName', e.name);
                } else {
                    this.$set(this.searchParams, 'customerName', '');
                }
                this.getListRequest();
            },
            querySearchAsync(queryString, cb) {
                spinCustomerPage({
                    name: queryString,
                    auditState: 1
                }).then(res => {
                    if (res.data.status === 200) {
                        cb(res.data.res ? res.data.res.map(x => {
                            return {
                                value: x.name,
                                ...x
                            };
                        }) : []);
                    }
                });
            },
            getListRequest() {
                this.searchBtnLoading = true;
                return reportProductionOrderTracking(this.searchParams).then(res => {
                    this.searchBtnLoading = false;
                    if (res.data.status === 200) {
                        let idx = 0;
                        this.orderOption = res.data.res.map((x) => {
                            if (idx > this.colors.length - 1) idx = 0;
                            this.$set(x, 'bgColor', this.colors[idx]);
                            idx++;
                            return x;
                        });
                        this.setColor(this.orderOption);
                    }
                });
            },
            onOrderItem(item) {
                this.selectOrderItem = this.selectOrderItem.id === item.id ? {} : item;
                if (Object.keys(this.selectOrderItem).length) {
                    this.setColor([this.selectOrderItem]);
                } else {
                    this.setColor(this.orderOption);
                }
            },
            onSearchBtn() {
                this.searchBtnLoading = true;
                this.selectOrderItem = {};
                this.getDependentData();
            },
            setColor(arr = []) {
                const cpData = JSON.parse(JSON.stringify(this.allWorkshopLayoutList));
                cpData.forEach(layoutItem => {
                    layoutItem.machineLayoutList.forEach(layoutMachineItem => {
                        layoutMachineItem.bgColor = '';
                        layoutMachineItem.noticeList = [];
                        arr.forEach((x) => {
                            x.processList.forEach(processItem => {
                                processItem.productOrderMachineList.forEach(machineItem => {
                                    if (machineItem.machineId === layoutMachineItem.machineId) {
                                        layoutMachineItem.scheduleEmpList = machineItem.scheduleEmpList ? JSON.parse(JSON.stringify(machineItem.scheduleEmpList)) : [];
                                        layoutMachineItem.noticeList.push({
                                            bgColor: x.bgColor,
                                            noticeOrderEntity: machineItem
                                        });
                                    }
                                });
                            });
                        });
                    });
                });
                this.allWorkshopLayoutList = cpData;
            },
            getAllWorkshopLayoutList() {
                this.allWorkshopLayoutList = [];
                return intelligenceReportWorkshopLayoutGetByWorkshopIds({ ids: this.searchParams.workshopIds }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res;
                        resData.map(item => {
                            item.machineLayoutList && item.machineLayoutList.length ? item.machineLayoutList.forEach(x => {
                                x.bgColor = '#808695';
                                x.noticeOrderEntity = {};

                                this.machineRunStateList.forEach(stateItem => {
                                    if (stateItem.machineId === x.machineId) {
                                        x.state = stateItem.state;
                                    }
                                });
                            }) : [];
                            return item;
                        });
                        this.allWorkshopLayoutList = resData.filter(item => item.machineLayoutList && item.machineLayoutList.length);
                        this.setColor(this.orderOption);
                    }
                });
            },
            async getDependentData() {
                await this.getWorkshopListRequest();
                await this.getMachineRunStateRequest();
                await this.getAllWorkshopLayoutList();
                await this.getListRequest();
            }
        },
        mounted() {
            this.workshopList = this.$store.state.user.userWorkshop.workshopList;
            this.$set(this.searchParams, 'workshopIds', this.workshopList ? this.workshopList.map(x => x.id) : []);
            this.getDependentData();
        },
        beforeRouteEnter(to, from, next) {
            next((_this) => {
                // 针对keepAlive等于true时,如果详情弹窗是打开状态，开启它的定时器
                if (_this.$refs.machineParamsDialog.showDialog) {
                    _this.$refs.machineParamsDialog.run();
                }
            });
        },
        beforeRouteLeave(to, from, next) {
            // 清除详情弹窗定时器
            this.$refs.machineParamsDialog.clearTimer();
            next();
        }
    };
</script>
<style scoped lang="scss">
    .order-tracking-container {
        height: 100vh;
        padding: 12px 16px;
        color: #515a6e;
        border-bottom: solid 1px #000;
        background: #180D37;
    }
</style>
